import com.google.appengine.api.datastore.Entity

import wyd.WydCategory

Entity transcation = new Entity('TranscationE')
def transcationTags = ''
if(params.transcation != null && params.transcation != '') {
	def matcher = (params.transcation =~ /^(\d+(.\d+)?) ([^#]*)(.*)$/)
	if(matcher.matches()) {
		transcation.amount = matcher[0][1] as float
		transcation.description = matcher[0][3].trim()
		transcationTags = matcher[0][4].trim()
	} else {
		def message = 'Transaction not in format...'
		if(params.json == null) {
			request.errorMessage = message

			forward 'transcation.groovy'
		} else {
			println message
		}
		
		return
	}
} else {
	transcation.amount = params.transcationAmount as float
	transcation.description = params.transcationDescription
	transcationTags = params.transcationTags
}

Date now = new Date()
transcation.userId = session.user.id
try {
	def s = "$params.transcationCreatedDateStg $params.transcationCreatedTimeStg"
	def createdTime = new Date().parse('dd-MM-yyyy HH:mm', s)
	use(groovy.time.TimeCategory) {
		int timeZoneHour = session.userTimeZoneHour as int
		int timeZoneMinute = session.userTimeZoneMinute as int
		transcation.createdTime = createdTime - timeZoneHour.hours - timeZoneMinute.minutes
	}
} catch(Throwable t) {
	t.printStackTrace()
	transcation.createdTime = now
}
transcation.updatedTime = now
transcation.save()

transcationTags.tokenize('#').each { tag ->
	Entity transcationTag = new Entity('TranscationTagE')
	transcationTag.name = tag.trim()
	transcationTag.transcationId = transcation.key.id
	transcationTag.userId = session.user.id
	transcationTag.createdTime = now
	transcationTag.updatedTime = now
	transcationTag.save()
}

memcache.delete(session.user.id + '-todayTranscations')
memcache.delete(session.user.id + '-weekTranscations')
memcache.delete(session.user.id + '-monthTranscations')

def infoMessage = "Expenses '$transcation.key.id $transcation.amount $transcation.description' created..."
if(params.json == null) {
	request.infoMessage = infoMessage

	forward 'transcationJQuery.groovy'
} else {
	println infoMessage
}